package com.hhit.zhgd.controller

import cn.dev33.satoken.stp.StpUtil
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.hhit.zhgd.domain.dto.RoleDTO
import com.hhit.zhgd.domain.entity.Role
import com.hhit.zhgd.domain.response.BaseResp
import com.hhit.zhgd.service.AdminService
import com.hhit.zhgd.service.RoleService
import com.hhit.zhgd.utils.toIntArr
import com.hhit.zhgd.utils.toMap
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
import java.util.*
import javax.validation.constraints.Min
import kotlin.collections.HashMap

@Validated
@RestController
class RoleController {
    @Autowired
    private var roleService: RoleService? = null

    @Autowired
    private var adminService: AdminService? = null

    @GetMapping("/roles")
    fun getRoleList(
        name: String?,
        root: Int?,
        status: Int?,
        @RequestParam(name = "page", defaultValue = "1") page: Long,
        @RequestParam(name = "size", defaultValue = "15") size: Long
    ): BaseResp<Page<HashMap<String, Any?>>?> {
        val param = HashMap<String, Any?>().also {
            it["name"] = name
            it["root"] = root
            it["status"] = status
        }
        val pages = Page<Role>(page, size)
        val list = roleService?.getList(pages, param)
        return BaseResp.success(list)
    }

    @GetMapping("/role/{id}")
    fun getRoleDetail(
        @PathVariable("id") @Min(
            value = 1,
            message = "参数错误"
        ) roleId: Int?
    ): BaseResp<HashMap<String, Any?>?> {
        val role = roleService?.getById(roleId)
        val data = role?.toMap()
        if (data != null) {
            data.remove("root")
            data.remove("permission")
            data["menu_ids"] = role.permission?.toIntArr()
        }
        return BaseResp.success(data)
    }


    @PostMapping("/role")
    fun addRole(@Validated(RoleDTO.Save::class) roleDto: RoleDTO): BaseResp<Any?> {
        val role = Role(
            name = roleDto.name,
            permission = "[${roleDto.menu_ids}]",
            status = roleDto.status,
            createTime = Date(),
            updateTime = Date()
        )
        roleService?.save(role)
        return BaseResp.success()
    }

    @PutMapping("/role")
    fun updateRole(@Validated(RoleDTO.Update::class) roleDto: RoleDTO): BaseResp<Any?> {
        val byId = roleService?.getById(roleDto.id) ?: return BaseResp.fail("角色不存在")
        return if (byId.root == 1) {
            BaseResp.fail("超级管理员角色不允许修改")
        } else {
            val role = Role(
                id = roleDto.id,
                name = roleDto.name,
                permission = "[${roleDto.menu_ids}]",
                status = roleDto.status,
                updateTime = Date()
            )
            roleService?.updateById(role)

            if (roleDto.status == 0) {
                //关闭权限时，将所有拥有该权限的用户下线
                val admins = adminService?.getRoleAdminAll(roleDto.id?.toInt() ?: -1)
                admins?.forEach {
                    StpUtil.logout(it["id"])
                }
            }
            BaseResp.success()
        }
    }

    @DeleteMapping("/role/{id}")
    fun deleteRole(@PathVariable("id") roleId: Int?): BaseResp<Any?> {
        val info = roleService?.getById(roleId)
        if (info == null || info.root == 1) {
            return BaseResp.fail("超级管理员角色不允许删除")
        }

        val admins = adminService?.getRoleAdminAll(roleId ?: -1)
        if (admins != null && admins.isNotEmpty()) {
            return BaseResp.fail("该角色下存在管理员，请先解除绑定")
        }

        val removeById = roleService?.removeById(roleId)
        return if (removeById == true) {
            BaseResp.success()
        } else {
            BaseResp.fail("删除失败")
        }
    }
}




















